﻿using Alarm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using tcp_server;
using udp_server;
using VehicleForm.Entity;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;
using static VehicleForm.VehicleForm;

namespace VehicleForm
{
    public partial class VehicleForm : Form
    {
        IPAddress localAddress;
        int port = 0;//IP端口
        public static string apiurl = ConfigurationManager.AppSettings["api"] == null ? "" : ConfigurationManager.AppSettings["api"].ToString();
        Queue<string> msgQueue = new Queue<string>();//消息队列
        /// <summary>
        /// 接入的客户端
        /// </summary>
        List<string> tcpClientList;
        /// <summary>
        /// 监听对象
        /// </summary>
        TcpListener tcpListener;
        public VehicleForm()
        {
            InitializeComponent();
            tcpClientList = new List<string>();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            port = Convert.ToInt32(this.txtPort.Text.Trim());//IP端口
            localAddress = IPAddress.Parse(this.txtIp.Text.Trim());//IP地址  
            this.lblAppStatus.Text = "运行中";
            Thread mainThread = new Thread(getMsgThreadAction);
            mainThread.Start();
            Thread queueThread = new Thread(queueThreadAction);
            queueThread.Start();
            this.btnStart.Enabled = false;
        }

        private void VehicleForm_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 处理数据线程
        /// </summary>
        private void queueThreadAction()
        {
            while (true)
            {
                if (msgQueue.Count > 0)
                {
                    string msg = msgQueue.Dequeue();

                    this.Invoke((MethodInvoker)delegate
                    {
                        listContent.Items.Add(new ListViewItem(new string[] { msg }));
                    });
                    var msgArray = msg.Split(',');
                    if (msgArray.Any())
                    {
                        //处理位置
                        if (msgArray[0].ToUpper().IndexOf("GGA") != -1)
                        {
                            GGA gGA = new GGA()
                            {
                                DataType = msgArray[0].Substring(3),
                                Time = msgArray[1],
                                Lat = msgArray[2],
                                N = msgArray[3],
                                Lon = msgArray[4],
                                E = msgArray[5],
                                FS = Convert.ToInt32(msgArray[6]),
                                NoSV = Convert.ToInt32(msgArray[7]),
                                HDOP = Convert.ToDouble(msgArray[8]),
                                msl = Convert.ToDouble(msgArray[9]),
                                M = msgArray[10],
                                Altref = string.IsNullOrEmpty(msgArray[11]) ? 0 : Convert.ToDouble(msgArray[11]),
                                M2 = msgArray[12],
                                DiffAge = string.IsNullOrEmpty(msgArray[13]) ? 0 : Convert.ToDouble(msgArray[13])
                            };
                            IDictionary<string, string> param = new Dictionary<string, string>();
                            param.Add("Coordinate", gGA.N + gGA.Lon + "," + gGA.E + gGA.Lon);//坐标
                            param.Add("Identifier", "12345678");
                            param.Add("ReturnsTime", gGA.Time);
                            WebUtils.DoPost(apiurl, param);
                        }
                    }
                    //处理消息
                }
            }
        }
        private void getMsgThreadAction()
        {
            //监听地址

            tcpListener = new TcpListener(localAddress, port);          //监听套接字
            tcpListener.Start();
            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // Enter the listening loop.
            while (true)
            {
                Console.Write("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                // You could also use server.AcceptSocket() here.
                TcpClient client = tcpListener.AcceptTcpClient();
                this.Invoke((MethodInvoker)delegate
                {
                    listDevice.Items.Add(new ListViewItem(new string[] { client.Client.RemoteEndPoint.ToString() }));
                });
                data = null;

                // Get a stream object for reading and writing
                NetworkStream stream = client.GetStream();

                int i;

                // Loop to receive all the data sent by the client.
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

                    msgQueue.Enqueue(data);
                }
            }


        }
        /// <summary>
        /// 更新程序时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerApp_Tick(object sender, EventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                this.Text = "车载数据接收-" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            });
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }
    }
}
